package booksystem.dao;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

// 定义一个用来被继承的对数据库进行基本操作的Dao
public class BaseDao<T> {

    private QueryRunner queryRunner = new QueryRunner(C3P0Connection.dataSource);

    // 通用的增删改操作
    public int update(String sql , Object...params){
        int count = 0;
        try {
            count = queryRunner.update(sql, params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }

    // 查询一条记录
    public T getBean(Class<T> type , String sql , Object...params){
        T t = null;
        try {
            t = queryRunner.query(sql, new BeanHandler<T>(type) ,  params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return t;
    }

    // 查询所有记录
    public List<T> getBeanList(Class<T> type , String sql , Object...params){
        List<T> list = null;
        try {
            list = queryRunner.query(sql, new BeanListHandler<T>(type),  params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    // 获取单值的方法，专门用来执行像select count(*)这样的sql语句
    public Object getSingleValue(String sql , Object...params){
        Object value = null;
        try {
            value = queryRunner.query(sql, new ScalarHandler(), params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return value;
    }
}
